/**
 * 移动端滑动组件
 * 支持水平/垂直滑动、自动播放、指示器等功能
 * 
 * @author 项目开发团队
 * @version 1.0.0
 */

import React, { useState, useEffect, useRef, useCallback } from 'react';
import './index.module.css';

const MobileSwiper = ({
  children,
  direction = 'horizontal',
  autoplay = false,
  autoplayInterval = 3000,
  showIndicators = true,
  showArrows = false,
  loop = true,
  className = '',
  onSlideChange,
  ...props
}) => {
  const [currentIndex, setCurrentIndex] = useState(0);
  const [isTransitioning, setIsTransitioning] = useState(false);
  const [touchStart, setTouchStart] = useState(null);
  const [touchEnd, setTouchEnd] = useState(null);
  const containerRef = useRef(null);
  const autoplayTimerRef = useRef(null);
  const childrenArray = React.Children.toArray(children);
  const totalSlides = childrenArray.length;

  // 开始自动播放
  const startAutoplay = useCallback(() => {
    if (autoplay && totalSlides > 1) {
      autoplayTimerRef.current = setInterval(() => {
        setCurrentIndex(prev => (prev + 1) % totalSlides);
      }, autoplayInterval);
    }
  }, [autoplay, totalSlides, autoplayInterval]);

  // 停止自动播放
  const stopAutoplay = useCallback(() => {
    if (autoplayTimerRef.current) {
      clearInterval(autoplayTimerRef.current);
      autoplayTimerRef.current = null;
    }
  }, []);

  // 处理触摸开始
  const handleTouchStart = useCallback((e) => {
    stopAutoplay();
    setTouchStart(e.touches[0].clientX);
  }, [stopAutoplay]);

  // 处理触摸移动
  const handleTouchMove = useCallback((e) => {
    setTouchEnd(e.touches[0].clientX);
  }, []);

  // 处理触摸结束
  const handleTouchEnd = useCallback(() => {
    if (!touchStart || !touchEnd) return;
    
    const distance = touchStart - touchEnd;
    const isLeftSwipe = distance > 50;
    const isRightSwipe = distance < -50;

    if (direction === 'horizontal') {
      if (isLeftSwipe && (loop || currentIndex < totalSlides - 1)) {
        goToNext();
      } else if (isRightSwipe && (loop || currentIndex > 0)) {
        goToPrev();
      }
    }

    setTouchStart(null);
    setTouchEnd(null);
  }, [touchStart, touchEnd, direction, currentIndex, totalSlides, loop]);

  // 下一张
  const goToNext = useCallback(() => {
    if (isTransitioning) return;
    
    setIsTransitioning(true);
    const nextIndex = loop ? (currentIndex + 1) % totalSlides : Math.min(currentIndex + 1, totalSlides - 1);
    setCurrentIndex(nextIndex);
    
    setTimeout(() => {
      setIsTransitioning(false);
      if (onSlideChange) {
        onSlideChange(nextIndex);
      }
    }, 300);
  }, [currentIndex, totalSlides, loop, isTransitioning, onSlideChange]);

  // 上一张
  const goToPrev = useCallback(() => {
    if (isTransitioning) return;
    
    setIsTransitioning(true);
    const prevIndex = loop ? (currentIndex - 1 + totalSlides) % totalSlides : Math.max(currentIndex - 1, 0);
    setCurrentIndex(prevIndex);
    
    setTimeout(() => {
      setIsTransitioning(false);
      if (onSlideChange) {
        onSlideChange(prevIndex);
      }
    }, 300);
  }, [currentIndex, totalSlides, loop, isTransitioning, onSlideChange]);

  // 跳转到指定索引
  const goToSlide = useCallback((index) => {
    if (isTransitioning || index === currentIndex) return;
    
    setIsTransitioning(true);
    setCurrentIndex(index);
    
    setTimeout(() => {
      setIsTransitioning(false);
      if (onSlideChange) {
        onSlideChange(index);
      }
    }, 300);
  }, [currentIndex, isTransitioning, onSlideChange]);

  // 初始化自动播放
  useEffect(() => {
    startAutoplay();
    return () => stopAutoplay();
  }, [startAutoplay, stopAutoplay]);

  // 鼠标悬停时暂停自动播放
  const handleMouseEnter = useCallback(() => {
    stopAutoplay();
  }, [stopAutoplay]);

  const handleMouseLeave = useCallback(() => {
    startAutoplay();
  }, [startAutoplay]);

  if (totalSlides === 0) {
    return null;
  }

  const translateValue = direction === 'horizontal' 
    ? `translateX(-${currentIndex * 100}%)` 
    : `translateY(-${currentIndex * 100}%)`;

  return (
    <div 
      className={`swiper ${className}`}
      onMouseEnter={handleMouseEnter}
      onMouseLeave={handleMouseLeave}
      {...props}
    >
      <div 
        ref={containerRef}
        className={`swiper-container ${direction}`}
        onTouchStart={handleTouchStart}
        onTouchMove={handleTouchMove}
        onTouchEnd={handleTouchEnd}
        style={{
          transform: translateValue,
          transition: isTransitioning ? 'transform 0.3s ease' : 'none'
        }}
      >
        {childrenArray.map((child, index) => (
          <div key={index} className="swiper-slide">
            {child}
          </div>
        ))}
      </div>

      {showIndicators && totalSlides > 1 && (
        <div className="swiper-indicators">
          {childrenArray.map((_, index) => (
            <button
              key={index}
              className={`swiper-indicator ${index === currentIndex ? 'active' : ''}`}
              onClick={() => goToSlide(index)}
              aria-label={`跳转到第 ${index + 1} 张`}
            />
          ))}
        </div>
      )}

      {showArrows && totalSlides > 1 && (
        <>
          <button
            className="swiper-arrow swiper-arrow-prev"
            onClick={goToPrev}
            disabled={!loop && currentIndex === 0}
            aria-label="上一张"
          >
            ‹
          </button>
          <button
            className="swiper-arrow swiper-arrow-next"
            onClick={goToNext}
            disabled={!loop && currentIndex === totalSlides - 1}
            aria-label="下一张"
          >
            ›
          </button>
        </>
      )}
    </div>
  );
};

export default MobileSwiper;
